﻿using Accessors;
using Common;
using Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LearnEnglishWords.Models
{
    public class CirclesModel
    {
        private CircleAccessor _circleAccessor;
        private Circle _currentCircle = null;

        public CirclesModel(CircleAccessor circleAccessor)
        {
            _circleAccessor = circleAccessor;
        }

        public event Action WordChanged;

        public async Task<List<Domain.CircleLookup>> GetCircleLookups()
        {
            var res = (await _circleAccessor.GetCirclesLookups()).ToList();
            return res;
        }

        public async Task SetAsCurrentCircle(Guid circleId)
        {
            _currentCircle = await _circleAccessor.GetCircle(circleId);
        }

        public Word CurrentWord
        {
            get
            {
                return _currentCircle == null ? null : _currentCircle.Current;
            }
        }

        public Word NextWord()
        {
            if (_currentCircle == null)
                return null;

            var res = _currentCircle.Next();
            DirectEvent.ThrowAsync(WordChanged);

            return res;
        }

        public Boolean IsCurrentCircleKnown()
        {
            if (_currentCircle == null)
                return true;

            return _currentCircle.IsKnown();
        }

        public async Task<Word> MarkAsKnown()
        {
            if (_currentCircle == null || _currentCircle.IsKnown())
                return null;

            _currentCircle.Current.KnownCounter++;
            _currentCircle.Current.LastKnownDate = DateTime.UtcNow;
            await _circleAccessor.UpdateWord(_currentCircle.Id, _currentCircle.Current);

            var res = _currentCircle.Next();            

            DirectEvent.ThrowAsync(WordChanged);

            return res;
        }

        public async Task SaveNewCircle(String name) 
        {
            _currentCircle = new Circle(Guid.NewGuid(), name, null);
            await _circleAccessor.InsertCircle(_currentCircle);
        }

        public async Task SaveNewWord(String engWord, String rusWord, String examples)
        {
            await SaveNewWord(_currentCircle.Id, engWord, rusWord, examples);
        }

        public async Task SaveNewWord(Guid circleId, String engWord, String rusWord, String examples)
        {
            var w = new Word(Guid.NewGuid()) 
            { 
                EnglishWord = engWord,
                RussianWord = rusWord,
                Examples = examples,
            };

            _currentCircle.Add(w);
            await _circleAccessor.InsertWord(w, circleId);

            DirectEvent.ThrowAsync(WordChanged);
        }
    }
}
